/**
 * 维保管理Mock数据
 */

import { MockMethod } from 'vite-plugin-mock';

import { ApprovalStatus, RequestType } from '#/api/core/maintenance';

/**
 * 生成Mock维保申请数据
 */
function generateMockRequests() {
  const requests = [];
  const drivers = ['张三', '李四', '王五', '赵六', '钱七'];
  const licensePlates = [
    '京A12345',
    '京B67890',
    '京C11111',
    '京D22222',
    '京E33333',
  ];

  for (let i = 1; i <= 50; i++) {
    const driverName = drivers[Math.floor(Math.random() * drivers.length)];
    const licensePlate =
      licensePlates[Math.floor(Math.random() * licensePlates.length)];
    const requestType =
      Math.random() > 0.5 ? RequestType.REPAIR : RequestType.MAINTENANCE;

    // 生成随机时间（最近30天内）
    const now = new Date();
    const randomHours = Math.floor(Math.random() * 30 * 24);
    const requestTime = new Date(now.getTime() - randomHours * 60 * 60 * 1000);

    // 生成随机描述
    const descriptions = [
      '车辆发动机异响，需要检查',
      '定期保养，更换机油和滤芯',
      '刹车系统故障，需要维修',
      '轮胎磨损严重，需要更换',
      '空调系统不制冷，需要检修',
      '电瓶电量不足，需要更换',
      '变速箱换挡不顺畅',
      '车辆底盘异响',
      '灯光系统故障',
      '雨刷器老化需要更换',
    ];

    // 生成随机图片URL（模拟多图）
    const imageCount = Math.floor(Math.random() * 3) + 1;
    const imageUrls = [];
    for (let j = 0; j < imageCount; j++) {
      imageUrls.push(`https://picsum.photos/400/300?random=${i}${j}`);
    }

    requests.push({
      requestId: i,
      vehicleId: Math.floor(Math.random() * 100) + 1,
      driverId: Math.floor(Math.random() * 50) + 1,
      licensePlate,
      driverName,
      requestType,
      description:
        descriptions[Math.floor(Math.random() * descriptions.length)],
      imageUrls: imageUrls.length > 0 ? imageUrls : undefined,
      requestTime: requestTime.toISOString(),
      approvalStatus: ApprovalStatus.PENDING,
    });
  }

  return requests;
}

const mockRequests = generateMockRequests();

export default [
  // 获取待审批列表
  {
    url: '/api/maintenance/pending',
    method: 'get',
    response: ({ query }) => {
      const {
        page = 1,
        pageSize = 20,
        licensePlate,
        driverName,
        requestType,
      } = query;

      let filteredRequests = mockRequests.filter(
        (request) => request.approvalStatus === ApprovalStatus.PENDING,
      );

      // 过滤条件
      if (licensePlate) {
        filteredRequests = filteredRequests.filter((request) =>
          request.licensePlate.includes(licensePlate),
        );
      }

      if (driverName) {
        filteredRequests = filteredRequests.filter((request) =>
          request.driverName.includes(driverName),
        );
      }

      if (requestType) {
        filteredRequests = filteredRequests.filter(
          (request) => request.requestType === requestType,
        );
      }

      // 分页
      const total = filteredRequests.length;
      const startIndex = (Number(page) - 1) * Number(pageSize);
      const endIndex = startIndex + Number(pageSize);
      const items = filteredRequests.slice(startIndex, endIndex);

      return {
        code: 200,
        data: {
          items,
          total,
          page: Number(page),
          pageSize: Number(pageSize),
        },
      };
    },
  },

  // 获取申请详情
  {
    url: '/api/maintenance/:requestId',
    method: 'get',
    response: ({ params }) => {
      const { requestId } = params;
      const request = mockRequests.find(
        (req) => req.requestId === Number(requestId),
      );

      if (!request) {
        return {
          code: 404,
          message: '申请不存在',
        };
      }

      return {
        code: 200,
        data: request,
      };
    },
  },

  // 审批申请
  {
    url: '/api/maintenance/approve',
    method: 'post',
    response: ({ body }) => {
      const { requestId } = body;
      const request = mockRequests.find((req) => req.requestId === requestId);

      if (!request) {
        return {
          code: 404,
          data: {
            success: false,
            message: '申请不存在',
          },
        };
      }

      // 更新申请状态
      request.approvalStatus = ApprovalStatus.APPROVED;
      request.approvalTime = new Date().toISOString();

      return {
        code: 200,
        data: {
          success: true,
          message: '审批成功',
        },
      };
    },
  },

  // 驳回申请
  {
    url: '/api/maintenance/reject',
    method: 'post',
    response: ({ body }) => {
      const { requestId, approvalNotes } = body;
      const request = mockRequests.find((req) => req.requestId === requestId);

      if (!request) {
        return {
          code: 404,
          data: {
            success: false,
            message: '申请不存在',
          },
        };
      }

      if (!approvalNotes || approvalNotes.trim() === '') {
        return {
          code: 400,
          data: {
            success: false,
            message: '请输入驳回原因',
          },
        };
      }

      // 更新申请状态
      request.approvalStatus = ApprovalStatus.REJECTED;
      request.approvalNotes = approvalNotes;
      request.approvalTime = new Date().toISOString();

      return {
        code: 200,
        data: {
          success: true,
          message: '驳回成功',
        },
      };
    },
  },
] as MockMethod[];
